import javax.swing.*;
import java.awt.event.*;
import java.net.*;
import java.io.*;
import java.util.Vector;
import java.util.ArrayList;
import java.util.HashMap;

import ru.edu.niimm.mapping.linguistic.NLPmodule;
//import org.apache.xmlrpc.webserver.WebServer;
//import org.apache.xmlrpc.server.PropertyHandlerMapping;
//import org.apache.xmlrpc.server.XmlRpcServerConfigImpl;
//import org.apache.xmlrpc.server.XmlRpcServer;
import org.apache.xmlrpc.XmlRpcException;
import org.apache.xmlrpc.WebServer;
import org.apache.xmlrpc.XmlRpcServer;
import org.apache.xmlrpc.XmlRpcClient;
import gate.util.GateException;
import com.hp.hpl.jena.rdf.model.ModelFactory;
import com.hp.hpl.jena.ontology.OntModel;
import com.hp.hpl.jena.ontology.OntModelSpec;
import com.hp.hpl.jena.ontology.Individual;


public class StartDialog extends JDialog {
    private JPanel contentPane;
    private JButton buttonOK;
    private JButton buttonCancel;
    private JTextField textField1;
    private JButton button1;



    public StartDialog() {
        setContentPane(contentPane);
        setModal(true);
        getRootPane().setDefaultButton(buttonOK);

        buttonOK.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                onOK();
            }
        });

        buttonCancel.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                onCancel();
            }
        });

        // call onCancel() when cross is clicked
        setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
        addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                onCancel();
            }
        });

        // call onCancel() on ESCAPE
        contentPane.registerKeyboardAction(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                onCancel();
            }
        }, KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);

        button1.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                onTest();
            }
        });
    }

    private void onOK() {
        // add your code here
//        int port = Integer.parseInt(textField1.getText());
        HashMap<String, String> wf = new HashMap<String, String>();
        NLPmodule nlp = new NLPmodule();

//        String docPath = "C:/servers/apache_webserver/Apache2/htdocs/momproject/mom/framework/TMP/FIELDS_TMP";
        String docPath = "C:/Users/смит/Documents/test4disser/4TEST/keyword_idx/rbm";
        String docPath2 = "C:/Users/смит/Documents/test4disser/4TEST/lemma_idx/rbm";
//        String docPath = "C:/servers/apache_webserver/Apache2/htdocs/momproject/mom/framework/ontostore/ontomuse/thesauri/rusaat/location";
//        ontostore\ontomuse\thesauri\rusaat\location

        File pth = new File(docPath);
        File[] docs =  pth.listFiles();

        int j = 0;
        int jj = 0;
        for(File doc : docs)
        {

            StringBuffer lemma = new StringBuffer("");
//  new StringBuffer("<?xml version=\"1.0\"?><aotData>");
            /*if (j++ > 500)
            {
                break;
            }*/
            StringBuffer strBuf = new StringBuffer();
            try {
                FileReader fr = new FileReader(doc);
                char[] buf = new char[500];
                while(fr.ready() && fr.read(buf) > 0)
                {
                    strBuf.append(buf);
                }
                fr.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
            } catch (IOException e) {
                e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
            }
            strBuf.trimToSize();

            String str = strBuf.toString();
//            .replaceAll("–", " ");
//            str = str.replaceAll("-", " ");
            str = str.replaceAll("[^А-Яа-я]", " ").toUpperCase();
//            str = str.replaceAll("[0-9]", " ");

            while(str.contains("  "))
            {
                str = str.replaceAll("  ", " ");
            }
            str = str.trim().toUpperCase();
            String[] words = str.split(" ");
            for(String word : words)
            {
              /*  if (jj++ > 2000)
                {
                    j=501;
                }*/
                if(!wf.containsKey(word))
                {
//                    lemma.append(nlp.lemmaConcat(word, "foo")).append("\n");
                    lemma.append(nlp.lemmaConcat(word));
                    wf.put(word, "1");
                }
            }

//            lemma.append("</aotData>");

        FileWriter fw = null;
        try {
            fw = new FileWriter(docPath2 + "/" +doc.getName() + ".lemma.txt");
            fw.write(lemma.toString());
            fw.flush();
            fw.close();
        } catch (IOException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }

        }



//        nlp.initForIndex("","ru");
//        try {
//            nlp.execOnFieldIndex("", "", new URL("http://localhost/tatneft/prilag.txt"), "ru");
//        } catch (GateException e) {
//            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
//        } catch (IOException e) {
//            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
//        }
//        runServer();
//        dispose();
    }

    private void onCancel() {

        NLPmodule nlp = new NLPmodule();
        try {
            String facetURL = "http://localhost/mom/framework/TMP/IDX_CLS_ONTO/1568.owl";
            nlp.execOnFolderIndex("11", facetURL, "C:\\servers\\apache_webserver\\Apache2\\htdocs\\momproject\\mom\\framework\\TMP\\VRM_ALL_FIELDS_TMP", "ru");
        } catch (GateException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        } catch (IOException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }

        // add your code here if necessary
        dispose();
    }

    public static void main(String[] args) {
        StartDialog dialog = new StartDialog();
        dialog.pack();
        dialog.runServer(8081);
        dialog.setVisible(true);
        System.exit(0);
    }

    public void runServer(int port)
    {
        WebServer webServer = new WebServer(port);
        webServer.addHandler("NLPmodule", new NLPmodule());
        webServer.start();
    }


    private void onTest() {

        OntModel resultModel = ModelFactory.createOntologyModel(OntModelSpec.OWL_LITE_MEM);
                    OntModel AATModel = ModelFactory.createOntologyModel(OntModelSpec.OWL_LITE_MEM);
                    AATModel.read("http://localhost/mom/framework/ontostore/ontomuse/thesauri/rusaat/base/rusaat.owl", "RDF/XML-ABBREV");
                    // задаем пространства имен в новой модели
                    resultModel.setNsPrefix("crm", "http://cidoc.ics.forth.gr#");
                    resultModel.setNsPrefix("nmrt", "http://www.tatar.museum.ru#");
                    resultModel.setNsPrefix("emku", "http://emku.ksu.ru#");
                    resultModel.setNsPrefix("miku", "http://miku.ksu.ru#");
                    resultModel.setNsPrefix("vrm", "http://www.museum.ru#");
                    resultModel.setNsPrefix("kgasu", "http://www.kgasu.ru#");
                    resultModel.setNsPrefix("benaki", "http://www.benaki.ru#");
                    resultModel.setNsPrefix("culthes", "http://thesaurus.niimm.edu.ru#");
                    resultModel.setNsPrefix("rusaat", "http://aat.cir.ru#");
                    resultModel.setNsPrefix("rbm", "http://www.rbm.ru#");
                    resultModel.add(AATModel);

        XmlRpcClient xmlrpc = null;
        try {
            xmlrpc = new XmlRpcClient("http://localhost:8081/RPC2");
        } catch (MalformedURLException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }



        String docPath = "C:\\servers\\apache_webserver\\Apache2\\htdocs\\momproject\\mom\\framework\\TMP\\FIELDS_TMP";
//        String docPath = "C:\\servers\\apache_webserver\\Apache2\\htdocs\\momproject\\mom\\framework\\ontostore\\lsa\\data\\_LSA\\rusaat\\1";
        File pth = new File(docPath);
        File[] docs =  pth.listFiles();
//        URL[] texts = new URL[ docs.length ];
        int j = 0;
        for(File doc : docs)
        {
            System.out.println("+++++++ INDEX ++++++++");
            Vector  params = new Vector();
            params.addElement("test");
            params.addElement("http://localhost/mom/framework/TMP/IDX_CLS_ONTO/-1364926237.owl");

            params.addElement("http://localhost/mom/framework/TMP/FIELDS_TMP/" + doc.getName());
//             params.addElement("http://localhost/mom/framework/ontostore/lsa/data/_LSA/rusaat/1/"+ doc.getName());
            try {
                Object objRes =  xmlrpc.execute("NLPmodule.execOnFieldIndex", params);
//                 descriptors = null;
                System.out.println("_ " + objRes.toString());
                Vector descriptors = (Vector) objRes;
                if(descriptors.size() == 0)
                {
                    System.out.println("nothing! for " + doc.getName());
                }
                else
                {
                    System.out.println("found descriptor(s) in " + doc.getName());

                    for(Object o : descriptors)
                    {
                        String descriptor = o.toString();
                        String NS2 = resultModel.getNsPrefixURI("rusaat");
                        Individual objectNode = resultModel.getIndividual(NS2 + descriptor);
                        System.out.println("_indexed with " + objectNode.getLabel("ru"));
                    }
                }
            } catch (org.apache.xmlrpc.XmlRpcException e) {
                e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
            } catch (IOException e) {
                e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
            }
        }

    }


}
